package weibo4android.androidexamples;

import java.util.List;


import cn.com.karl.logic.MainService;
import cn.com.karl.logic.Task;
import cn.com.karl.net.NetUtil;

import weibo4android.Paging;
import weibo4android.Status;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.androidexamples.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;

public class HomeActivity2 extends Activity implements IWeiboActivity{
	private ListView listView;
	List<Status> friendsTimeline;
	StringBuilder stringBuilder;
	private TextView textUserName;
	private Button head_new;
	private Button head_refresh;
	private ProgressDialog p;
	
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			friendsTimeline = (List<Status>) msg.obj;

			listView.setAdapter(new UserAdapter());
			textUserName.setText(msg.getData().getString("userName"));
			p.dismiss();
			
			head_new.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent=new Intent(HomeActivity2.this,NewWeiboActivity.class);
					startActivity(intent);
				}
			});
			
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(
				WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
				WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
		setContentView(R.layout.home);
		if(MainService.isRun==true){
			
		}else{
		Intent service=new Intent(this,MainService.class);
	    startService(service);
		}
	    textUserName=(TextView) findViewById(R.id.head_userName);
	    head_new=(Button) this.findViewById(R.id.head_new);	
		head_refresh=(Button) this.findViewById(R.id.head_refresh);
		head_refresh.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				MainService.addActivity(HomeActivity2.this);
				MainService.newTask(new Task(Task.HOMEREFRESH,null));
			}
		});
		listView = (ListView) findViewById(R.id.home_list);
		p = ProgressDialog.show(this, "", "正在加载，请稍候  . . .  ", true);
		
		new Thread() {
			@Override
			public void run() {
				SharedPreferences preferences = getSharedPreferences("ss",
						Context.MODE_PRIVATE);
				String token = preferences.getString("token", "");
				String tokenSecret = preferences.getString("tokenSecret", "");
				Weibo weibo = OAuthConstant.getInstance().getWeibo();
				// weibo.setToken(OAuthConstant.getInstance().getToken(),
				// OAuthConstant.getInstance().getTokenSecret());
				weibo.setToken(token, tokenSecret);
				String userName=preferences.getString("userName", "");
				try {
					friendsTimeline = weibo
							.getHomeTimeline();
					Message msg = handler.obtainMessage();
					msg.obj = friendsTimeline;
					msg.getData().putString("userName", userName);
					handler.sendMessage(msg);
				} catch (WeiboException e) {
					e.printStackTrace();
				}
			};
		}.start();

	}
  
	private class UserAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		List<Status> friendsTimeline;
		private Context context;
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return friendsTimeline.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return friendsTimeline.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			Status status = friendsTimeline.get(position);
			inflater = (LayoutInflater) HomeActivity2.this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.home_item, null);
				ImageView imageIcon = (ImageView) convertView
						.findViewById(R.id.home_image);

				imageIcon.setBackgroundDrawable(NetUtil.getNetImage(status
						.getUser().getProfileImageURL()));
				TextView textView = (TextView) convertView
						.findViewById(R.id.home_title);
				textView.setText(status.getUser().getName() + "说：");
				TextView textContent = (TextView) convertView
						.findViewById(R.id.home_content);
				textContent.setText(status.getText());
				TextView textTime = (TextView) convertView
						.findViewById(R.id.home_timeout);
				textTime.setTextSize(10);
				textTime.setText(status.getCreatedAt().toLocaleString());
              
				TextView home_item_swich=(TextView) convertView.findViewById(R.id.home_item_swich);
				if(null != status.getRetweeted_status()){
				home_item_swich.setText(status.getRetweeted_status().getText().toString());
				}else{
					LinearLayout layout=(LinearLayout) convertView.findViewById(R.id.home_item_layout);
					layout.setVisibility(View.GONE);
				}
			}
			return convertView;
		}

	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		
		if(keyCode==KeyEvent.KEYCODE_BACK){
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("你确定退出吗？")
			       .setCancelable(false)
			       .setPositiveButton("确定", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			               HomeActivity2.this.finish();
			                //停止服务
			              // Context.stopService();
			               Intent it=new Intent(HomeActivity2.this,MainService.class);
					       HomeActivity2.this.stopService(it);
			               android.os.Process.killProcess(android.os.Process.myPid());
			               android.os.Process.killProcess(android.os.Process.myTid());
			               android.os.Process.killProcess(android.os.Process.myUid()); 
			           }
			       })
			       .setNegativeButton("返回", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();
			return true;
		}
		
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void refresh(Object... params) {
		// TODO Auto-generated method stub
		  
	}
    
}
